package com.example.experiment4sqlite

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.example.experiment4sqlite.bean.UserInfo
import com.example.experiment4sqlite.utils.UserDbHelper

class UpdateUserActivity : AppCompatActivity() {
    private var info: UserInfo? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_update_user)

        val user = UserDbHelper(this)
        var db = user.writableDatabase

        val updateButton = findViewById<Button>(R.id.button_update)
        val editTextUserName = findViewById<EditText>(R.id.input_new_user_name)
        val editTextAge = findViewById<EditText>(R.id.input_new_age)
        val searchButton = findViewById<Button>(R.id.button_search)
        searchButton.setOnClickListener {
            val stuNumber = findViewById<EditText>(R.id.input_stu_number).text.toString()
            if (stuNumber == ""){
                Toast.makeText(applicationContext, "请先输入信息", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            info = user.search(db, stuNumber)
            Log.d(TAG, "info now is $info")
            if (info != null) {
                editTextUserName.setText(info!!.userName)
                editTextAge.setText(info!!.age.toString())
            } else {
                Toast.makeText(applicationContext, "数据库中无学号为${stuNumber}的数据", Toast.LENGTH_SHORT).show()
            }
        }
        // TODO: 更好的做法：没有变化的情况使按钮变得不可点击
        updateButton.setOnClickListener {
            if (editTextUserName.text.toString() == ""){
                Toast.makeText(applicationContext, "请先输入信息", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            db = user.writableDatabase
            user.updateUser(db,
                info!!.id,
                editTextUserName.text.toString(),
                info!!.stuNumber,
                info!!.sex,
                editTextAge.text.toString().toInt())
            Toast.makeText(applicationContext, "学号为${info!!.stuNumber}的信息更新成功", Toast.LENGTH_SHORT).show()
        }
    }
}
